package com.wg.wuge.study.algo.link;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Linked
 *
 * @Author wugeng
 * @date 2021/8/5 上午11:33
 **/
public class Linked {

    /**
     * 单链表反转(使用栈的方式)
     */
    private Node reverse(Node node) {
        if (node == null || node.next == null) {
            return node;
        }
        Stack<Node> stack = new Stack<>();
        while(node != null) {
            stack.push(node);
            node = node.next;
        }
        Node temp = stack.pop();
        Node header = temp;
        while(!stack.isEmpty()) {
            temp.next = stack.pop();
            temp = temp.next;
        }
        temp.next = null;
        return header;
    }

    /**
     * 单链表反转(使用递归的方式)
     */
    private Node reverseList(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node list = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return list;
    }

    /**
     * 判断是否为回文链表
     * @param head
     * @return
     */
    public boolean isPalindrome(Node head) {
        if (head == null) {
            return false;
        }
        if (head.next == null) {
            return true;
        }
        List<Integer> list = new ArrayList<>();
        while(head.next != null) {
            list.add(head.val);
            head = head.next;
        }
        Stack s = new Stack();
        for (int i = 0; i < list.size()/2; i++) {
            if (!list.get(i).equals(list.get(list.size() - i - 1))) {
                return false;
            }
        }
        return true;


    }
    public static void main(String[] args) {
        Node node = new Node();
        Node header = node;
        node.val = 1;
        node.next = new Node();
        node = node.next;
        node.val = 2;
        node.next = new Node();
        node = node.next;
        node.val = 3;
        node.next = new Node();
        node = node.next;
        node.val = 4;
        node.next = new Node();
        node = node.next;
        node.val = 5;
        Linked linked = new Linked();
        Boolean result = linked.isPalindrome(header);
        System.out.println(result);
//        linked.pri?nt(result);
    }

    private void print(Node node) {
        if (node == null) {
            return;
        }
        while(node!= null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

}
